package com.vrv.netmgr.assets.chart;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.SeriesSelection;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.vrv.common.GlobalConstants;
import com.vrv.common.UrlPrefix;
import com.vrv.common.util.HttpClientToServer;
import com.vrv.netmgr.R;

/**
 * 本地设备类型统计
 * 
 * @author gaopei
 * 
 */
@SuppressLint("HandlerLeak")
public class DeviceTypeStatActivity extends Activity {
    private static final String TAG = DeviceTypeStatActivity.class.getSimpleName();
    private static final boolean DEBUG = true && GlobalConstants.DEBUG;

	/** 为统计图开辟的区域 */
	private LinearLayout layout;
	List<String> listLabel = new ArrayList<String>();
	List<Long> listVal = new ArrayList<Long>();
	/** 饼形图 */
	GraphicalView pieChartView = null;
	CategorySeries dataset;
	DefaultRenderer renderer;
	/**
	 * 等待对话框
	 */
	private ProgressDialog progressDialog;	
	/**
	 * 查询
	 */
	private static final int QUERY_OS = 1;
	private static final int NET_ERR = 99;	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		if(DEBUG) Log.v(TAG, "onCreate()");
		
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.alarm_region_statistics_layout);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.common_title);
        initView();
		progressDialog = ProgressDialog.show(DeviceTypeStatActivity.this, "",
				"查询中...", true, true);
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				getDataFromServer();
				handler.sendEmptyMessage(QUERY_OS);
			}
		}).start();
	}
	
	/**
	 * 处理器
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if(DEBUG) Log.v(TAG, "handler.handleMessage()");
			
			progressDialog.dismiss();
			switch (msg.what) {
			case QUERY_OS:
				buildPieChartView();
				break;
			case NET_ERR:
				Toast.makeText(DeviceTypeStatActivity.this, "网络连接失败",
						Toast.LENGTH_LONG).show();
				break;
			}
		}
	};

	private void initView() {
		if(DEBUG) Log.v(TAG, "initView()");
		
		TextView titleView = (TextView) findViewById(R.id.title_text);
		titleView.setText("本地设备类型统计");

		// 返回按钮
		ImageButton backBtn = (ImageButton) findViewById(R.id.backBtn);
		backBtn.setVisibility(View.VISIBLE);
		backBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});

		// 初始化chart的渲染位置
		layout = (LinearLayout) findViewById(R.id.bar_chart);
	}

	public void buildPieChartView() {
		if(DEBUG) Log.v(TAG, "buildPieChartView()");
		
		/** 统计图所需数据 */
		int[] colors = new int[] { Color.BLUE, Color.GREEN, Color.MAGENTA,
				Color.YELLOW, Color.RED,
				getResources().getColor(R.color.darkblue),
				getResources().getColor(R.color.brown),
				getResources().getColor(R.color.orange), 
				getResources().getColor(R.color.purple), 
				getResources().getColor(R.color.darkorchid)};
		Object[] labels = listLabel.toArray();
		Object[] vals = listVal.toArray();// new long[] { 0L, 349L, 0L, 116L, 135L, 8L, 0L };
		renderer = buildCategoryRenderer(colors);
		renderer.setZoomButtonsVisible(false);
		renderer.setZoomEnabled(true);
		renderer.setChartTitleTextSize(40);
		renderer.setDisplayValues(true);
		renderer.setLabelsColor(Color.BLACK);
		renderer.setShowLabels(true);
		renderer.setClickEnabled(true);
		dataset = buildCategoryDataset("", labels, vals);
		if(pieChartView != null) layout.removeView(pieChartView);
		pieChartView = ChartFactory.getPieChartView(this, dataset, renderer);
		layout.addView(pieChartView, new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		pieChartView.setOnClickListener(new MyClickListener());
	}

	private class MyClickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			if(DEBUG) Log.v(TAG, "MyClickListener.onClick()");
			
			SeriesSelection seriesSelection = pieChartView
					.getCurrentSeriesAndPoint();
			if (seriesSelection != null) {
				for (int i = 0; i < dataset.getItemCount(); i++) {
					renderer.getSeriesRendererAt(i).setHighlighted(
							i == seriesSelection.getPointIndex());
				}
				pieChartView.repaint();
//				Toast.makeText(
//						DeviceTypeStatActivity.this,
//						"Chart data point index "
//								+ seriesSelection.getPointIndex() + " selected"
//								+ " point value=" + seriesSelection.getValue(),
//						Toast.LENGTH_SHORT).show();
			}
		}

	}

	public CategorySeries buildCategoryDataset(String title, Object[] labels,
			Object[] values) {
		if(DEBUG) Log.v(TAG, "buildCategoryDataset()");
		
		CategorySeries series = new CategorySeries(title);
		int k = 0;
		for (Object value : values) {
			series.add((String)labels[k++], (Long) value);
		}
		return series;
	}

	public DefaultRenderer buildCategoryRenderer(int[] colors) {
		if(DEBUG) Log.v(TAG, "buildCategoryRenderer()");
		
		DefaultRenderer renderer = new DefaultRenderer();
		renderer.setLabelsTextSize(20);
		renderer.setLegendTextSize(20);
		renderer.setShowLegend(false);
		renderer.setMargins(new int[] { 0, 30, 15, 0 });
		for (int i = 0; i < listLabel.size(); i++) {
			SimpleSeriesRenderer r = new SimpleSeriesRenderer();
			r.setColor(colors[i]);
			renderer.addSeriesRenderer(r);
		}
		return renderer;
	}

	// 查询所有数据
	public void getDataFromServer() {
		if(DEBUG) Log.v(TAG, "getDataFromServer()");
		
		Map<String, String> map = new HashMap<String, String>();
		boolean retVal = qryRegisterStat(map);
		if (!retVal)
			handler.sendEmptyMessage(NET_ERR);
	}

	public boolean qryRegisterStat(Map<String, String> map) {
		if(DEBUG) Log.v(TAG, "qryRegisterStat()");
		
		boolean retVal = false;
		HttpClientToServer httpClientToServer = new HttpClientToServer();
		String urlPrefix = new UrlPrefix(getApplicationContext()).getUrlPrefix();
		String urlAddr = urlPrefix + "/deviceInfo/getDeviceResourceByType.do";
		String response = httpClientToServer.doPost(urlAddr, map);
		if (HttpClientToServer.DO_POST_ERR.equals(response) || HttpClientToServer.DO_POST_EXCEPT.equals(response))
			return retVal;
		
		try {
			JSONTokener jsonParser = new JSONTokener(response);
			JSONObject jsonObj = (JSONObject) jsonParser.nextValue();
			retVal = jsonObj.getBoolean("success");
			if (!retVal) return retVal;
			int count = jsonObj.getInt("totalRecords");
			if (count < 1) return retVal;
			JSONArray jArr = jsonObj.getJSONArray("records");
			listLabel.clear();
			listVal.clear();
			long sum = 0L;
			for (int i = 0; i < jArr.length(); i++) {
//				JSONObject jObj = (JSONObject) jArr.opt(i);
//				long num = jObj.getLong("Num");
//				sum += num;
//				listLabel.add(jObj.getString("DevFirstType") + ":" + num);
//				listVal.add(num);
				
				/**update by zxb 20130719*/
				JSONObject jObj = (JSONObject) jArr.opt(i);
				String type = jObj.getString("DevFirstType");
				long amount = jObj.getLong("Num");
				if (type.equals("设备总数")) {
					type = "未注册设备";
					amount -= sum;
				}
				sum += amount;
				listLabel.add(type + ":" + amount);
				listVal.add(amount);
			}
			for(int j = 0; j < listLabel.size(); j++){
				listLabel.set(j, listLabel.get(j) + "," + new BigDecimal(listVal.get(j) * 100 / sum).setScale(2, BigDecimal.ROUND_HALF_UP) + "%");	
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return retVal;
	}

	@Override
	public void onBackPressed() {
		if(DEBUG) Log.v(TAG, "onBackPressed()");
		
		finish();
		overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
		super.onBackPressed();
	}
}
